package leecode.topic14;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * 示例 1:
 *
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 * 示例 2:
 *
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Topic14 {

    public static String longestCommonPrefix(String[] strs) {
        if(strs == null || strs.length < 1){
            return "";
        }
        String result = strs[0];
        for (int i = 1 ; i < strs.length; i ++){
            char[] resultArr = result.toCharArray();
            char[] currArr = strs[i].toCharArray();
            if(currArr.length == 0){
                return "";
            }
            int min = resultArr.length > currArr.length ? currArr.length : resultArr.length;
            for(int j = 0 ; j < min; j++){
                if(resultArr[j] != currArr[j]){
                    if(j == 0) {
                        return "";
                    }
                    result = result.substring(0, j);
                    break;
                }else if(j == min -1){
                    result = result.substring(0, min);
                }
            }
        }
        return  result;
    }

    public static void main(String[] args) {
        String[] array1 = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix(array1));
        String[] array2 = {"dog","racecar","car"};
        System.out.println(longestCommonPrefix(array2));
        String[] array3 = {"aa","a"};
        System.out.println(longestCommonPrefix(array3));
    }
}
